<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Manager extends MX_Controller {


	function __construct(){

		parent::__construct();

        $this->load->library('form_validation');

        $this->load->library('manager/my_form_validation');

		$this->load->library('auth/tank_auth');
		if (!Modules::run('auth/is_login'))
			redirect('/auth/login/manager');

		$this->load->model('manager_model');
		$this->load->library('pagination');		

	}
	
	public function index()
	{
		
		$this->load->view('page_manager');
	}

	function myaccount(){

		require_once('application/modules/auth/libraries/phpass-0.1/PasswordHash.php');

		$user_id = Modules::run('auth/get_user_id');
		
		$username = Modules::run('auth/get_username');

		$this->load->model('auth/tank_auth/users');

		$user = $this->users->get_user_by_id($user_id, TRUE); 

		$data['username'] 	= $user->username;
		$data['title'] 		= $user->title;
		$data['first_name'] = $user->first_name;
		$data['last_name'] 	= $user->last_name;
		$data['email'] 		= $user->email;

		$data['list_title'] = array('Mr.'=> 'Mr.', 'Mrs.'=> "Mrs.");

		$this->form_validation->set_error_delimiters('<span class="error-form">', '</span>');
		$this->form_validation->set_message('required', ' %s is required ');
		$this->form_validation->set_message('is_unique', 'Username already exists. Please choose another username.');
		if($this->input->post('username') == $username ){
			$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|max_length[50]');
		}else{
			$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|max_length[50]|is_unique[users.username]');
		}

		//$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|max_length[50]');
		$this->form_validation->set_rules('title', 'Title', 'trim|required|xss_clean');
		$this->form_validation->set_rules('first_name', 'First Name', 'trim|required|xss_clean|max_length[100]');
		$this->form_validation->set_rules('last_name', 'Last Name', 'trim|required|xss_clean|max_length[100]');

		if($user_id == '' || $this->input->post('password')){
			$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length['.$this->config->item('password_min_length', 'tank_auth').']|max_length['.$this->config->item('password_max_length', 'tank_auth').']|alpha_dash');
			$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean|matches[password]');
		}

		if ($this->form_validation->run()) {	

			$data_update['username'] 	= $this->form_validation->set_value('username');
			$data_update['title'] 		= $this->form_validation->set_value('title');
			$data_update['first_name'] 	= $this->form_validation->set_value('first_name');
			$data_update['last_name'] 	= $this->form_validation->set_value('last_name');
			$data_update['modified'] 	= date('Y-m-d H:i:s');

			$this->users->update_user($user_id, $data_update);

			if($this->form_validation->set_value('password') != ''){
				$hasher = new PasswordHash(
				$this->config->item('phpass_hash_strength', 'tank_auth'),
				$this->config->item('phpass_hash_portable', 'tank_auth'));
				$hashed_password = $hasher->HashPassword($this->form_validation->set_value('password'));

				$data_password = array(
					'password' => $hashed_password
				);
							
				$this->users->update_user($user_id,$data_password);
			} 

			$message = array('alert-info','Data successfully saved.');

			$this->session->set_flashdata('message', $message);

			redirect('manager/myaccount');
			exit();
		}

		$this->load->view('user_manager', $data);
	}

	function store(){

		$user_id = Modules::run('auth/get_user_id');

		$this->load->model('content/content_model');

		$store = $this->manager_model->get_store($user_id);

		$data['nama_toko'] 	= $store->nama_toko;
		$data['judul_toko'] = $store->judul_toko;
		$data['description'] = $store->description;
		$data['logo'] 		= $store->logo;
		$data['alamat'] 	= $store->alamat;
		$data['telepon'] 	= $store->telepon;
		$data['hp'] 		= $store->hp;
		$data['kode_pos'] 	= $store->kode_pos;
		$data['kota'] 		= $store->kota;
		$data['provinsi'] 	= $store->provinsi;		
		$data['negara'] 	= $store->negara;

		$data['list_country'] 	= $this->content_model->get_country();
		$data['list_region'] 	= $this->content_model->get_region_by_country_id(100);

		$data['curent_country'] = $store->negara;
		$data['curent_region'] 	= $store->provinsi;

		$this->form_validation->set_error_delimiters('<span class="error-form">', '</span>');
		$this->form_validation->set_message('required', ' %s is required ');

		$this->form_validation->set_rules('judul_toko', 'Store Title', 'trim|required|xss_clean');
		$this->form_validation->set_rules('description', 'Description', 'trim|required|xss_clean');
		$this->form_validation->set_rules('logo_file', 'Logo', 'trim|xss_clean');
		$this->form_validation->set_rules('alamat', 'Address', 'trim|required|xss_clean|max_length[225]');
		$this->form_validation->set_rules('telepon', 'Telephone', 'trim|required|xss_clean|is_natural');
		$this->form_validation->set_rules('hp', 'Handphone', 'trim|required|xss_clean|is_natural');
		$this->form_validation->set_rules('kota', 'City', 'trim|required|xss_clean');
		$this->form_validation->set_rules('kode_pos', 'Post Code', 'trim|required|xss_clean|is_natural');
		$this->form_validation->set_rules('provinsi', 'Region / State', 'trim|required|xss_clean');
		$this->form_validation->set_rules('negara', 'Country', 'trim|required|xss_clean');

		$config['upload_path']   = './data/upload/';
		$config['allowed_types'] = 'gif|jpg|png|bmp';
		$config['encrypt_name']  = TRUE;
		$config['max_size']  	= 600;
		
		$this->load->library('upload', $config);

		$upload_logo = false;

		if(isset($_FILES['logo']['name']) && $_FILES['logo']['name'] != ''){
			if ( ! $this->upload->do_upload('logo') )
			{
				$message = array('alert-error', $this->upload->display_errors() );
				$this->session->set_flashdata('message', $message);
				redirect('manager/store');
				exit();
			}

			$data_file = $this->upload->data();
			$upload_logo = true;

			// create thumbnail
			if (isset($data_file['full_path']) && $data_file['full_path'] != ''){
				$this->load->library('image_lib');
				$config = array('source_image' => $data_file['full_path'], 
								'new_image' => './data/thumb/', 
								'maintain_ration' => true, 
								'width' => 150,
					            'height' => 130);

				$this->image_lib->initialize($config);
				$this->image_lib->resize();
				$this->image_lib->clear();
			}

			if ($this->input->post('logo_file', true) != ''){
				$file_name = $this->input->post('logo_file', true);

				@unlink('./data/upload/'.$file_name);
				@unlink('./data/thumb/'.$file_name);
			}
			

		}

		if (!isset($error)){

			if ($this->form_validation->run()) {

				if (!isset($data_file['file_name']) && $this->form_validation->set_value('logo_file') != '')
					$data_file['file_name'] = $this->form_validation->set_value('logo_file');

				if ($this->input->post('del_i', true) == 1 && !$upload_logo){
					$data_file['file_name'] = '';

					if ($this->input->post('logo_file', true) != ''){
						$file_name = $this->input->post('logo_file', true);

						@unlink('./data/upload/'.$file_name);
						@unlink('./data/thumb/'.$file_name);
					}
				}

				
				$data_update['judul_toko'] 	= $this->form_validation->set_value('judul_toko');
				$data_update['description'] = $this->form_validation->set_value('description');
				$data_update['logo'] 		= $data_file['file_name'];
				$data_update['alamat'] 		= $this->form_validation->set_value('alamat');
				$data_update['telepon'] 	= $this->form_validation->set_value('telepon');
				$data_update['hp'] 			= $this->form_validation->set_value('hp');
				$data_update['kode_pos'] 	= $this->form_validation->set_value('kode_pos');
				$data_update['kota'] 		= $this->form_validation->set_value('kota');
				$data_update['provinsi'] 	= $this->form_validation->set_value('provinsi');
				$data_update['negara'] 		= $this->form_validation->set_value('negara');
				$data_update['date_modified'] = date('Y-m-d H:i:s');				

				$this->manager_model->update_store($user_id,$data_update);

				//var_dump($data_update);
				//exit();

				$message = array('alert-info','Data successfully saved.');

				$this->session->set_flashdata('message', $message);

				redirect('manager/store');
				exit();

			}
		}

		$this->load->view('store_manager', $data);
	}

	function product($page=''){

		$user_id = Modules::run('auth/get_user_id');
		
		$limit = 10;

		if ($page == '')
			$page = 0;

		$where = '';

		$data['products'] = $this->manager_model->get_list_product($user_id,$page,$limit,$where);

		$config_pagination['base_url']    = site_url('manager/product');
		$config_pagination['total_rows']  = count($this->manager_model->get_list_product($user_id,'0','0',$where));
		$config_pagination['per_page']    = 10;
		$config_pagination['uri_segment'] = 3;
		$config_pagination['num_links']   = 4;

		//pagination style
		$config_pagination['full_tag_open'] = '<div class="pagination"><ul>';
		$config_pagination['full_tag_close'] = '</ul></div>';

		$config_pagination['first_link'] = 'First';
		$config_pagination['first_tag_open']  = '<li>';
		$config_pagination['first_tag_close'] = '</li>';

		$config_pagination['last_link'] = 'Last';
		$config_pagination['last_tag_open']  = '<li>';
		$config_pagination['last_tag_close'] = '</li>';

		$config_pagination['next_link'] = '&gt;';
		$config_pagination['next_tag_open']  = '<li>';
		$config_pagination['next_tag_close'] = '</li>';

		$config_pagination['prev_link'] = '&lt;';
		$config_pagination['prev_tag_open'] = '<li>';
		$config_pagination['prev_tag_close'] = '</li>';

		$config_pagination['cur_tag_open'] = '<li class="disabled"><a href="#">';
		$config_pagination['cur_tag_close'] = '</a></li>';

		$config_pagination['num_tag_open'] = '<li>';
		$config_pagination['num_tag_close'] = '</li>';

		$this->pagination->initialize($config_pagination); 

		$data['pagination'] = $this->pagination->create_links();

		$this->load->view('product_list_manager', $data);
	}

	function form_product($product_id=''){

		$user_id = Modules::run('auth/get_user_id');

		$data['product_id'] 	= '';
		$data['image_file'] 	= '';
 		$data['product_name'] 	= '';
  		$data['description'] 	= '';
  		$data['price'] 			= '';
  		$data['status'] 		= '';
  		$data['tags'] 			= '';
  		$data['category_id'] 	= '';
  		$data['option_id'] 		= '';
  		$data['quantity'] 		= '';
  		$data['subtract_stock'] = '';
  		$data['weight'] 		= '';
  		$data['weight_class'] 	= '';
  		$data['length'] 		= '';
  		$data['width'] 			= '';
  		$data['height'] 		= '';
  		$data['length_class'] 	= '';
  		$data['edit'] 			= false;

  		$data['product_options'] = array();

  		$data['shipping_method'] = array();

  		$data['session_shipping_method'] = array();

  		if (!isset($_POST['product_name'])) {
  			$this->session->unset_userdata('shipping');
  		}
  		else {
  			$data['session_shipping_method'] = $this->session->userdata('shipping');
  		}  		

  		if (!empty($product_id)){

  			$data['edit'] = true;

  			$product = $this->manager_model->get_product($product_id);

  			$data['product_id'] 	= $product->product_id;
	 		$data['product_name'] 	= $product->product_name;
	 		$data['image_file'] 	= $product->image_file;
	  		$data['description'] 	= $product->description;
	  		$data['price'] 			= $product->price;
	  		$data['status'] 		= $product->status;
	  		$data['tags'] 			= $product->tags;
	  		$data['category_id'] 	= $product->category_id;
	  		$data['option_id'] 		= $product->option_id;
	  		$data['quantity']		= $product->quantity;
	  		$data['subtract_stock'] = $product->subtract_stock;
	  		$data['weight'] 		= $product->weight;
	  		$data['weight_class'] 	= $product->weight_class;
	  		$data['length'] 		= $product->length;
	  		$data['width'] 			= $product->width;
	  		$data['height'] 		= $product->height;
	  		$data['length_class'] 	= $product->length_class;

	  		$data['product_options'] = $this->manager_model->get_product_option($product_id);

	  		$data['shipping_method'] = $this->manager_model->get_product_shipping($product_id);

	  		//var_dump($data['product_options']);

  		}

  		$this->form_validation->set_error_delimiters('<span class="error-form">', '</span>');
		$this->form_validation->set_message('required', ' %s is required ');

		$this->form_validation->set_rules('product_id', 'Product ID', 'trim|xss_clean');
		$this->form_validation->set_rules('product_name', 'Product Name', 'trim|required|xss_clean');
		$this->form_validation->set_rules('description', 'Description', 'trim|required|xss_clean');
		$this->form_validation->set_rules('price', 'Price', 'trim|required|xss_clean|max_length[20]|callback_cek_price_value');
		$this->form_validation->set_rules('quantity', 'Quantity', 'trim|required|xss_clean|max_length[4]|is_natural_no_zero');

		$this->form_validation->set_rules('subtract_stock', 'Subtract Stock', 'trim|required|xss_clean');
		$this->form_validation->set_rules('status', 'Status', 'trim|required|xss_clean');
		$this->form_validation->set_rules('category', 'Category', 'trim|required|xss_clean');
		$this->form_validation->set_rules('tags', 'Tags', 'trimxss_clean');

		$this->form_validation->set_rules('weight', 'Weight', 'trim|xss_clean');
		$this->form_validation->set_rules('weight_class', 'wWight Class', 'trim|xss_clean');

		$this->form_validation->set_rules('length', 'Length', 'trim|xss_clean');
		$this->form_validation->set_rules('width', 'Width', 'trim|xss_clean');
		$this->form_validation->set_rules('height', 'Height', 'trim|xss_clean');
		$this->form_validation->set_rules('length_class', 'Length Class', 'trim');

		$this->form_validation->set_rules('image_file_name', 'image_file_name', 'trim|xss_clean');

		if(isset($_POST['product_id'])){

			if ($this->form_validation->run() == TRUE){

				if(!$this->cek_price_value($this->form_validation->set_value('price'))) {
					$message = array('alert-error', 'Please input a valid price!');
					$this->session->set_flashdata('message', $message);
					redirect('manager/form_product/'.$product_id);
					exit();
				}
			}
		}

		$config['upload_path']   = './data/upload/';
		$config['allowed_types'] = 'gif|jpg|png|bmp';
		$config['encrypt_name']  = TRUE;
		$config['max_size']  	= 600;

		$this->load->library('upload', $config);

		$upload_image = false;

		if(isset($_FILES['image_file']['name']) && $_FILES['image_file']['name'] != ''){
			if ( ! $this->upload->do_upload('image_file') )
			{
				$message = array('alert-error', $this->upload->display_errors() );
				$this->session->set_flashdata('message', $message);
				redirect('manager/form_product/'.$product_id);
				exit();
			}

			$data_file = $this->upload->data();
			$upload_image = true;

			// create thumbnail
			if (isset($data_file['full_path']) && $data_file['full_path'] != ''){
				$this->load->library('image_lib');
				$config = array('source_image' => $data_file['full_path'], 
								'new_image' => './data/thumb/', 
								'maintain_ration' => true, 
								'width' => 150,
					            'height' => 130);

				$this->image_lib->initialize($config);
				$this->image_lib->resize();
				$this->image_lib->clear();
			}

			if ($this->input->post('image_file_name', true) != ''){
				$file_name = $this->input->post('image_file_name', true);

				@unlink('./data/upload/'.$file_name);
				@unlink('./data/thumb/'.$file_name);
			}		

		}

		if (!isset($error)){

			if ($this->form_validation->run($this)) {

				if (!isset($data_file['file_name']) && $this->form_validation->set_value('image_file_name') != '')
						$data_file['file_name'] = $this->form_validation->set_value('image_file_name');

					if ($this->input->post('del_i', true) == 1 && !$upload_image){
						$data_file['file_name'] = '';

						if ($this->input->post('image_file_name', true) != ''){
							$file_name = $this->input->post('image_file_name', true);

							@unlink('./data/upload/'.$file_name);
							@unlink('./data/thumb/'.$file_name);
						}
					}


				$kode_product = random_string('nozero', 4);

				if ($this->form_validation->set_value('product_id') == ''){					
					
					$store = $this->manager_model->get_store($user_id);

					$data_save['user_id'] 		= $user_id;
					$data_save['toko_id'] 		= $store->toko_id;
					$data_save['product_name'] 	= $this->form_validation->set_value('product_name');
					$data_save['description'] 	= $this->form_validation->set_value('description');
					$data_save['price'] 		= $this->form_validation->set_value('price');
					$data_save['quantity'] 		= $this->form_validation->set_value('quantity');
					$data_save['subtract_stock'] = $this->form_validation->set_value('subtract_stock');
					$data_save['status'] 		= $this->form_validation->set_value('status');
					$data_save['category_id'] 	= $this->form_validation->set_value('category');
					$data_save['tags'] 			= $this->form_validation->set_value('tags');
					$data_save['weight'] 		= $this->form_validation->set_value('weight');
					$data_save['weight_class'] 	= $this->form_validation->set_value('weight_class');
					$data_save['length'] 		= $this->form_validation->set_value('length');
					$data_save['width'] 		= $this->form_validation->set_value('width');
					$data_save['height'] 		= $this->form_validation->set_value('height');
					$data_save['length_class'] 	= $this->form_validation->set_value('length_class');
					$data_save['image_file'] 	= isset($data_file['file_name']) ? $data_file['file_name'] : '';
					$data_save['date_add'] 		= date('Y-m-d H:i:s');

					//var_dump($data_save);
					//exit();

					$product_id = $this->manager_model->save_product($data_save, true);

					//update seo url
					$data_update['product_seo_name'] = strtolower(url_title($this->form_validation->set_value('product_name'))).'-'.$product_id;
					
					$this->manager_model->update_product($product_id,$data_update);	

					//option product
					$option = $this->input->post('option', true);

					if(is_array($option)) {
						foreach ($option as $key_op => $val_op) {
							
							$product_option['product_id']	= $product_id;
							$product_option['option_name'] 	= trim(str_replace(' ', '', $val_op['value'])); 
							$product_option['option_value'] = trim($val_op['option_value']); 
							$product_option['quantity'] 	= trim($val_op['option_qt']); 
							$product_option['subtract_stock'] = trim($val_op['option_st_stock']); 
							$product_option['price'] 		= trim($val_op['option_price']); 
							$product_option['image'] 		= '';

							if ($product_option['option_value'] != '')
							$this->manager_model->save_product_option($product_option);

						}
					}

					//shipping method
					$data_shipping = $this->session->userdata('shipping');

					foreach ($data_shipping as $key_s => $val_s) {

						$product_shipping['product_id'] = $product_id;
						$product_shipping['shipping_method'] = $val_s['shipping_method'];
						$product_shipping['location'] 	= $val_s['location'];
						$product_shipping['price'] 		= $val_s['price'];
						$product_shipping['date_add'] 	= date('Y-m-d H:i:s');

						$this->manager_model->save_product_shipping($product_shipping);

					}

					$this->session->unset_userdata('shipping');

					$message = array('alert-info','Data successfully saved.');

					$this->session->set_flashdata('message', $message);

					redirect('manager/product');
					exit();
				}
				else{

					$store = $this->manager_model->get_store($user_id);
					$product_id = $this->form_validation->set_value('product_id');

					$data_update['user_id'] 		= $user_id;
					$data_update['toko_id'] 		= $store->toko_id;
					$data_update['product_name'] 	= $this->form_validation->set_value('product_name');
					$data_update['product_seo_name'] = strtolower(url_title($this->form_validation->set_value('product_name'))).'-'.$product_id;
					$data_update['description'] 	= $this->form_validation->set_value('description');
					$data_update['price'] 			= $this->form_validation->set_value('price');
					$data_update['quantity'] 		= $this->form_validation->set_value('quantity');
					$data_update['subtract_stock'] 	= $this->form_validation->set_value('subtract_stock');
					$data_update['status'] 			= $this->form_validation->set_value('status');
					$data_update['category_id'] 	= $this->form_validation->set_value('category');
					$data_update['tags'] 			= $this->form_validation->set_value('tags');
					$data_update['weight'] 			= $this->form_validation->set_value('weight');
					$data_update['weight_class'] 	= $this->form_validation->set_value('weight_class');
					$data_update['length'] 			= $this->form_validation->set_value('length');
					$data_update['width'] 			= $this->form_validation->set_value('width');
					$data_update['height'] 			= $this->form_validation->set_value('height');
					$data_update['length_class'] 	= $this->form_validation->set_value('length_class');
					$data_update['image_file'] 		= isset($data_file['file_name']) ? $data_file['file_name'] : '';
					$data_update['date_add'] 		= date('Y-m-d H:i:s');					

					//var_dump($data_update);
					//exit();

					$option = $this->input->post('option', true);

					if(is_array($option)) {

						foreach ($option as $key_op => $val_op) {

							$product_option_id = '';

							if (isset($val_op['product_option_id']) && $val_op['product_option_id'] != '')
								$product_option_id = trim($val_op['product_option_id']); 
							
							$product_option['product_id']	= $product_id;						
							$product_option['option_name'] 	= trim(str_replace(' ', '', $val_op['value'])); 
							$product_option['option_value'] = trim($val_op['option_value']); 
							$product_option['quantity'] 	= trim($val_op['option_qt']); 
							$product_option['subtract_stock'] = trim($val_op['option_st_stock']); 
							$product_option['price'] 		= trim($val_op['option_price']); 
							$product_option['image'] 		= '';

							if ($product_option_id == '' && $product_option['option_value'] != ''){
								//save
								$this->manager_model->save_product_option($product_option);
							}
							elseif ($product_option_id != '' && $product_option['option_value'] != '') {
								//update
								$this->manager_model->update_product_option($product_option_id,$product_option);
							}

						}
					}

					$option_delete = $this->input->post('op_del_value', true);

					if(!$option_delete)
						$option_delete = array();

					foreach ($option_delete as $key_od => $product_option_id) {
						$this->manager_model->delete_product_option($product_option_id,$product_id);
					}

					$this->manager_model->update_product($product_id,$data_update);					

					$message = array('alert-info','Data successfully Updated.');

					$this->session->set_flashdata('message', $message);

					redirect('manager/product');
					exit();
				}
			}

		}

  		$data['list_status'] = array(1=>'Enabled', 0=>'Disabled');
  		$data['list_subtract_stock'] = array(1=>'Yes', 0=>'No');

  		$weight_class = $this->manager_model->get_product_weight_class();

  		foreach ($weight_class as $key => $val) {
  			$data['list_weight_class'][$val->unit] = $val->title;
  		}

  		$length_class = $this->manager_model->get_product_length_class();

  		foreach ($length_class as $key => $val) {
  			$data['list_length_class'][$val->unit] = $val->title;
  		}

		$data['list_category'] = $this->manager_model->get_category();

  		//var_dump($data);

		$this->load->view('product_form_manager', $data);
	}

	function delete_product($product_id){

		if ($product_id == '')
			redirect('manager/product');

		$user_id = Modules::run('auth/get_user_id');

		$this->manager_model->delete_product($product_id, $user_id);

		$message = array('alert-info','Data successfully Deleted.');

		$this->session->set_flashdata('message', $message);

		redirect('manager/product');

	}

	function cek_price_value($val){

		if(!preg_match('/^[0-9]+.[0-9]{0,4}$/', $val))
		{
			$this->form_validation->set_message('price', 'The %s field is not valid!');
			return FALSE;
		}
		else
		{
			$value = $val + 0 ;
			if($value == 0){
				$this->form_validation->set_message('price', 'The %s field is not Valid!');
				return FALSE;
			}
			else{
				return TRUE;
			}
			
		}
	}


	function transactions(){
		$this->load->view('page_manager');
	}

	function detail_tranction($order_id){
		$this->load->view('page_manager');
	}

	function get_region($country){

		$this->load->model('content/content_model');

		$data_country = $this->content_model->get_country_by_name($country);

		$country_id = $data_country->country_id;

		$data['region'] = $this->content_model->get_region_by_country_id($country_id);

		$this->load->view('get_region', $data);
	}
}

/* End of file manager.php */
